import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './home.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Popup, SearchBar } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import icon_home_hotfill from '@/assets/icon_home_hotfill.png'
import icon_home_more from '@/assets/icon_home_more.png'
import icon_home_copy from '@/assets/icon_home_copy.png'

import icon_transfer from '@/assets/icon_transfer.png'
import icon_receive from '@/assets/icon_receive.png'
import icon_earn from '@/assets/icon_earn.png'
import icon_add_white from '@/assets/icon_add_white.png'

import icon_nav_menu from "@/assets/icon_nav_menu.png"
import icon_nav_add_app from '@/assets/icon_nav_add_app.png'

import NavigateBar from "@/components/NavigateBar";
import { getCoins } from "@/store/actions/coins";
import { getUserAccounts, getUserWallet } from "@/store/actions/user";
import { getCoinInfo, isUnvalidUserInfo, setAssetDetailInfo, setCoinInfo, setManageWalletCoinType, setTransferInfo } from "@/utils/storage";
import BottomTabBar from "@/components/BottomTabBar/bottomTabBar";
import { toCopyText, toEllipsisWalletAddress } from "@/utils/utils";
import AddToHomeDialog from "@/components/AddToHomeDialog/AddToHomeGifDialog";
import { LangVnd } from '@/utils/langVnd';


/**
 * 登录页
 */
export default function Home() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //loading状态
    const [transferMaskVisible, setTransferMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);

    // 当前币
    const [curCoinName, setCurCoinName] = useState('')

    // 当前 assets 列表
    const [curAssetList, setCurAssetList] = useState([])

    // 当前 coin 列表
    const [curCoinList, setCurCoinList] = useState([])
    const [curCoinListTemp, setCurCoinListTemp] = useState([])

    // 当前 wallet
    const [curWallet, setCurWallet] = useState({})

    // 当前 wallet fliter
    const [curTransferText, setCurTransferText] = useState("")

    // 文案翻译
    const [curLang, setCurLang] = useState(LangVnd);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 判断是否需要重登录
        if (isUnvalidUserInfo()) {
            history.replace('/login')
            return
        }

        // 查询币
        doGetCoins();

        //打点
        doHitEvent("HOME_START")

        return () => {
            //打点
            doHitEvent("HOME_END")
        }
    }, []);

    // 点击 nav back
    const onHandleNavBackClick = () => {
        history.push('/mywalletlist');
    };

    // 点击 wallet manage
    const onHandleWalletManageClick = () => {
        // 获取当前币
        const cacheCoinInfo = getCoinInfo();
        let cacheCoinType = cacheCoinInfo.coinType || "";

        // 缓存
        setManageWalletCoinType(cacheCoinType);

        // 跳转管理页
        history.push('/mywalletmanage');
    };

    // 点击 wallet address copy
    const onHandleWalletAddressCopyClick = (address) => {
        toCopyText(address);
    };

    // 点击 Transfer
    const onHandleMenuTransfer = () => {
        //history.push('/transfer');
        setTransferMaskVisible(true);
    };

    // 点击 Receive
    const onHandleMenuReceive = () => {
        history.push('/receive');
    };

    // 点击 Earn
    const onHandleMenuEarn = () => {
        history.push('/earn');
    };

    // 点击 asset item
    const onHandleAssetItemClick = (index) => {
        if (curAssetList.length > index) {
            const item = curAssetList[index];
            console.log('点击 asset item: ');
            console.log(item);

            let assetInfo = {};
            assetInfo.name = item.coinName || "";
            assetInfo.coinType = item.coinType || "";
            // 缓存
            setAssetDetailInfo(assetInfo)

            history.push('/assetdetail');
        }
    };


    // 点击 transfer item
    const onHandleTransferItemClick = (item) => {
        if (item) {
            console.log('点击 transfer item: ');
            console.log(item);

            let transferInfo = {};
            transferInfo.name = item.coinName || "";
            transferInfo.coinType = item.coinType || "";
            // 缓存
            setTransferInfo(transferInfo)

            history.push('/transfer');
        }
    };

    // 过滤 transfer item
    const onHandleTransferTextChanged = (text) => {
        console.log('更新 输入框: ' + text);
        // 更新 输入框
        setCurTransferText(text);

        // 更新列表
        let textUp = text.toUpperCase();
        let sourceList = [...curCoinListTemp];
        let tempList = [];
        for (let i = 0; i < sourceList.length; i++) {
            let item = sourceList[i];
            if (item.coinName.indexOf(textUp) !== -1) {
                tempList.push(item);
            } else if (item.name.indexOf(textUp) !== -1) {
                tempList.push(item);
            }
        }
        setCurCoinList(tempList);
    };

    // 获取币种信息 返回
    const onDoGetCoinsCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            if (data.length > 0) {
                // {
                //     "symbol": "BTC",
                //     "coinName": null,
                //     "name": "BTC",
                //     "mainCoinType": "0",
                //     "coinType": "0",
                //     "logo": null,
                //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
                //     "balance": 0
                // }

                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    let coinName = item.coinName || "";
                    let name = item.name || "";
                    let symbol = item.symbol || "";
                    let mainCoinType = item.mainCoinType || "";
                    let coinType = item.coinType || "";
                    let logo = item.logo || icon_add_white;
                    let address = item.address || "";

                    if (coinName.length === 0) {
                        coinName = symbol;
                    }

                    item.coinName = coinName;
                    item.name = name;
                    item.logo = logo;
                    item.address = address;
                    item.symbol = symbol;
                    item.mainCoinType = mainCoinType;
                    item.coinType = coinType;
                }

                // 缓存
                setCurCoinListTemp(data);
                setCurCoinList(data);

                // 判断当前是否有缓存
                // 获取当前币
                const cacheCoinInfo = getCoinInfo();
                let cacheMainCoinType = cacheCoinInfo.mainCoinType || "";
                let cacheCoinType = cacheCoinInfo.coinType || "";
                if ((cacheCoinType.length <= 0) || (cacheMainCoinType.length <= 0)) {
                    // 更新名称
                    let item = data[0];

                    // 缓存
                    setCoinInfo(item);

                    if (item.name.length > 0) {
                        setCurCoinName(item.name);
                    } else {
                        setCurCoinName(item.symbol);
                    }

                    // 缓存
                    cacheMainCoinType = item.mainCoinType;
                    cacheCoinType = item.coinType;

                } else {
                    if (cacheCoinInfo.name.length > 0) {
                        setCurCoinName(cacheCoinInfo.name);
                    } else {
                        setCurCoinName(cacheCoinInfo.symbol);
                    }
                }

                // 获取accounts信息
                doGetUserAccounts(cacheMainCoinType);

                // 获取钱包信息
                doGetUserWallet(cacheCoinType);
            }
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // 获取accounts信息 返回
    const onDoGetUserAccountsCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            if (data.length > 0) {
                // {
                //     "logo": null,
                //     "coinType": "0",
                //     "coinName": "BTC",
                //     "balance": 0,
                //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR"
                // }

                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    let coinName = item.coinName || "";
                    let coinType = item.coinType || "";
                    let logo = item.logo || icon_add_white;
                    let address = item.address || "";

                    item.coinName = coinName;
                    item.logo = logo;
                    item.address = address;
                    item.coinType = coinType;
                }

                // 保存
                setCurAssetList(data);
            }
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };


    // 获取钱包信息 返回
    const onDoGetUserWalletCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "walletId": 47,
            //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
            //     "name": null,
            //     "coinUnit": "BTC",
            //     "balance": 0
            // }

            let name = data.name || "";
            let coinUnit = data.coinUnit || "";
            if (name.length <= 0) {
                data.name = coinUnit;
            }

            // 保存
            setCurWallet(data);
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取币种信息
    const doGetCoins = async () => {
        console.log("doGetCoins: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getCoins(onDoGetCoinsCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取accounts信息
    const doGetUserAccounts = async (mainCoinType) => {
        console.log("doGetUserAccounts: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserAccounts(mainCoinType, onDoGetUserAccountsCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取钱包信息
    const doGetUserWallet = async (coinType) => {
        console.log("doGetUserWallet: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserWallet(coinType, onDoGetUserWalletCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    return (
        <div className="pageRoot">
            <NavigateBar theme="white" showLogout={false} leftIcon={icon_nav_menu} rightIcon={icon_nav_add_app} onAddFavorite={() => { setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskVisible(true) }} onGoBack={onHandleNavBackClick}>{curCoinName}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull pageContentPaddingHorizontal16px">
                {/* 顶部模块 */}
                <div className={styles.homeTop}>
                    <img className={styles.homeTopTipsImage} alt="" src={icon_home_hotfill} />

                    {/* 钱包名称 */}
                    <div className={styles.homeWalletNameRow}>
                        <div className={styles.homeWalletName}>{curWallet.name}</div>
                        <img className={styles.homeWalletManager} alt="" src={icon_home_more} onClick={onHandleWalletManageClick} />
                    </div>

                    {/* 钱包地址 */}
                    <div className={styles.homeWalletAddressRow}>
                        <div className={styles.homeWalletAddress}>{toEllipsisWalletAddress(curWallet.address)}</div>
                        <img className={styles.homeWalletAddressCopyIcon} alt="" src={icon_home_copy} onClick={() => { onHandleWalletAddressCopyClick(curWallet.address) }} />
                    </div>
                </div>

                {/* 菜单 列表 */}
                <div className="pageContentRowFull pageMarginTop10px">
                    <div className="pageContentRowFull pageCardGrayBorder">
                        {/* Transfer */}
                        <div className={styles.homeMenuColumn} onClick={onHandleMenuTransfer}>
                            <img className={styles.homeMenuImage} alt="" src={icon_transfer} />
                            <div className={styles.homeMenuTitle}>{curLang.homeTransfer}</div>
                        </div>

                        {/* Receive */}
                        <div className={styles.homeMenuColumn} onClick={onHandleMenuReceive}>
                            <img className={styles.homeMenuImage} alt="" src={icon_receive} />
                            <div className={styles.homeMenuTitle}>{curLang.homeReceive}</div>
                        </div>

                        {/* Earn */}
                        <div className={styles.homeMenuColumn} onClick={onHandleMenuEarn}>
                            <img className={styles.homeMenuImage} alt="" src={icon_earn} />
                            <div className={styles.homeMenuTitle}>{curLang.homeEarn}</div>
                        </div>
                    </div>
                </div>

                {/* Assets 模块 */}
                <div className="pageContentColumnFull pageMarginTop26px">
                    <div className={styles.homeAssets}>
                        <div className={styles.homeAssetsTitle}>{curLang.homeAssets}</div>
                        <div className={styles.homeAssetsDot}></div>
                    </div>

                    {/* Assets 列表 */}
                    <div className={styles.homeAssetsList}>
                        {curAssetList && curAssetList.map((value, index) => {
                            return (
                                <div className={styles.homeAssetsListItem} key={index} onClick={() => { onHandleAssetItemClick(index) }}>
                                    <img className={styles.homeAssetsListItemIcon} alt="" src={value.logo} />
                                    <div className={styles.homeAssetsListItemName}>{value.coinName}</div>
                                    <div className={styles.homeAssetsListItemAmount}>{value.balance}</div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"> </div>

            {/* tab bar */}
            <BottomTabBar page="home" />

            {/* 左上角切换 */}
            <Popup
                visible={transferMaskVisible}
                onMaskClick={() => {
                    setTransferMaskVisible(false)
                }}
                bodyStyle={{
                    height: '80vh',
                    borderTopLeftRadius: '16px',
                    borderTopRightRadius: '16px'
                }}
                destroyOnClose
            >
                <div className={styles.homeSearchBarContainer}>
                    <div className={styles.homeSarchBarLine}></div>
                    <div className={styles.homeSarchBarTitle}>{curLang.homeSelectAsset}</div>
                    <div className={styles.homeSarchBarValue}>{curCoinName}</div>
                    <SearchBar
                        style={{ width: '100%' }}
                        placeholder='Input Token Name'
                        value={curTransferText}
                        onChange={v => {
                            onHandleTransferTextChanged(v);
                        }} />
                </div>

                <div className={styles.homePopupContainer}>
                    {/* Assets 列表 */}
                    <div className={styles.homeAssetsList}>
                        {curCoinList && curCoinList.map((value, index) => {
                            return (
                                <div className={styles.homeAssetsListItem} key={index} onClick={() => { onHandleTransferItemClick(value) }}>
                                    <img className={styles.homeAssetsListItemIcon} alt="" src={value.logo} />
                                    <div className={styles.homeAssetsListItemName}>{value.coinName}</div>
                                    <div className={styles.homeAssetsListItemAmount}>{value.balance}</div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </Popup>

            {/* 添加桌面快捷方式 */}
            <AddToHomeDialog visible={addHomeMaskVisible} onClose={() => { setAddHomeMaskVisible(false) }}></AddToHomeDialog>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}